﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace PHPostClient
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            Uri uri = new Uri("http://localhost/PriceHistoryService/GetPriceHistorywithPOST.ashx");
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.BeginGetRequestStream(new AsyncCallback(RequestProceed), request);
        }

        void RequestProceed(IAsyncResult asyncResult)
        {
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asyncResult));
            postDataWriter.Write("ticker=MSFT");
            postDataWriter.Write("&startdate=1-1-2009");
            postDataWriter.Write("&enddate=1-10-2009");
            postDataWriter.Close();
            request.BeginGetResponse(new AsyncCallback(ResponseProceed), request);
        }
        void ResponseProceed(IAsyncResult asyncResult)
        {
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
            string responseString = responseReader.ReadToEnd();

            XDocument xReturn = XDocument.Parse(responseString);

            IEnumerable<TimeSeriesData> myTimeSeries = from item in xReturn.Descendants("TimeSeries")
                                                       select new TimeSeriesData
                                                       {
                                                           open = Convert.ToDouble(item.Element("Open").Value)


                                                       };

            Dispatcher.BeginInvoke(() => _items.ItemsSource = myTimeSeries);
        }

    }
}
